#!/usr/bin/env python3

import re
import subprocess

try:
    with open('last_log_filename', 'r') as f:
        last_log_filename = f.read().strip()
except:
    exit(1)

with open(last_log_filename, 'r') as f:
    lines = f.readlines()

found = ''
for line in lines:
    if result := re.findall("\[.*?\] \[\d+\] \[INFO\] Starting worker \[(\d+)\]", line.strip()):
        # print(line.strip())
        found = result[0]


def findFatherPid(pid : int) -> int:
    ppid_command_output = subprocess.check_output(f'ps -o ppid -p {pid}'.split()).decode('utf-8').split('\n')
    return int(ppid_command_output[1])


last_worker_pid = int(found)
father_pid = findFatherPid(last_worker_pid)
pid_list = [last_worker_pid, father_pid]
while father_pid != 1:
    last_worker_pid = father_pid
    father_pid = findFatherPid(father_pid)
    pid_list.append(father_pid)

with open(last_log_filename, 'a') as f:
    f.write('pid list: ')
    f.write('->'.join([str(i) for i in pid_list]))
    f.write('\n')

print(last_worker_pid)